<template>
  <el-dialog v-model="dialogVisible" title="版本管理" width="1000px" :close-on-click-modal="false">
    <div class="version-manage">
      <!-- 当前版本信息 -->
      <el-card shadow="never" class="current-version-card">
        <template #header>
          <div class="card-header">
            <h3>当前版本</h3>
            <el-tag type="success" size="large">{{ currentVersion.version }}</el-tag>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>预案名称：</label>
              <span>{{ currentVersion.planName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>版本状态：</label>
              <el-tag :type="getStatusTagType(currentVersion.status)">
                {{ getStatusText(currentVersion.status) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ formatDateTime(currentVersion.createTime) }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>创建人：</label>
              <span>{{ currentVersion.creator }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>生效时间：</label>
              <span>{{ formatDateTime(currentVersion.effectiveTime) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>执行次数：</label>
              <span>{{ currentVersion.executionCount }} 次</span>
            </div>
          </el-col>
        </el-row>

        <div class="info-item">
          <label>版本说明：</label>
          <p class="description">{{ currentVersion.description || '暂无说明' }}</p>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="showCreateVersionDialog">
          <el-icon>
            <Plus />
          </el-icon>
          创建新版本
        </el-button>
        <el-button type="success" @click="showCompareDialog" :disabled="selectedVersions.length !== 2">
          <el-icon>
            <View />
          </el-icon>
          版本对比
        </el-button>
        <el-button type="warning" @click="showMergeDialog" :disabled="selectedVersions.length < 2">
          <el-icon>
            <View />
          </el-icon>
          版本合并
        </el-button>
        <el-button type="info" @click="exportVersionHistory">
          <el-icon>
            <Download />
          </el-icon>
          导出历史
        </el-button>
      </div>

      <!-- 版本历史 -->
      <el-card shadow="never" class="history-card">
        <template #header>
          <div class="card-header">
            <h3>版本历史</h3>
            <div class="header-actions">
              <el-input v-model="searchKeyword" placeholder="搜索版本" size="small" style="width: 200px" clearable>
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-button type="primary" size="small" @click="refreshVersions">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table :data="filteredVersions" stripe @selection-change="handleSelectionChange" row-key="id">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="version" label="版本号" width="120">
            <template #default="{ row }">
              <div class="version-cell">
                <el-tag :type="getVersionTagType(row)" size="small">
                  {{ row.version }}
                </el-tag>
                <el-tag v-if="row.isCurrent" type="success" size="small" style="margin-left: 5px">
                  当前
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="版本说明" min-width="200">
            <template #default="{ row }">
              <span class="description-text">{{ row.description || '暂无说明' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="executionCount" label="执行次数" width="100">
            <template #default="{ row }">
              {{ row.executionCount }} 次
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewVersion(row)">
                查看
              </el-button>
              <el-button type="success" size="small" @click="activateVersion(row)"
                :disabled="row.isCurrent || row.status === 'obsolete'">
                激活
              </el-button>
              <el-button type="warning" size="small" @click="rollbackVersion(row)" :disabled="row.isCurrent">
                回滚
              </el-button>
              <el-button type="danger" size="small" @click="deleteVersion(row)" :disabled="row.isCurrent">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalVersions"
            :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 创建版本对话框 -->
    <el-dialog v-model="createVersionVisible" title="创建新版本" width="600px" :close-on-click-modal="false" append-to-body>
      <el-form ref="createVersionFormRef" :model="createVersionForm" :rules="createVersionRules" label-width="100px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="createVersionForm.version" placeholder="如：v2.0" />
        </el-form-item>
        <el-form-item label="基于版本" prop="baseVersion">
          <el-select v-model="createVersionForm.baseVersion" placeholder="请选择基于版本" style="width: 100%">
            <el-option v-for="version in versionOptions" :key="version.id" :label="version.version"
              :value="version.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本类型" prop="type">
          <el-select v-model="createVersionForm.type" placeholder="请选择版本类型" style="width: 100%">
            <el-option label="主要版本" value="major" />
            <el-option label="次要版本" value="minor" />
            <el-option label="补丁版本" value="patch" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本说明" prop="description">
          <el-input v-model="createVersionForm.description" type="textarea" :rows="4" placeholder="请输入版本说明" />
        </el-form-item>
        <el-form-item label="立即激活">
          <el-switch v-model="createVersionForm.activate" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createVersionVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreateVersion" :loading="createVersionLoading">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 版本对比对话框 -->
    <el-dialog v-model="compareVisible" title="版本对比" width="1200px" :close-on-click-modal="false" append-to-body>
      <div class="version-compare">
        <div class="compare-header">
          <div class="version-info">
            <h4>{{ compareVersions[0]?.version || '版本1' }}</h4>
            <span>{{ formatDateTime(compareVersions[0]?.createTime) }}</span>
          </div>
          <div class="compare-divider">VS</div>
          <div class="version-info">
            <h4>{{ compareVersions[1]?.version || '版本2' }}</h4>
            <span>{{ formatDateTime(compareVersions[1]?.createTime) }}</span>
          </div>
        </div>

        <div class="compare-content">
          <el-tabs v-model="compareTab" type="border-card">
            <el-tab-pane label="基本信息" name="basic">
              <div class="compare-table">
                <table class="comparison-table">
                  <thead>
                    <tr>
                      <th>属性</th>
                      <th>{{ compareVersions[0]?.version }}</th>
                      <th>{{ compareVersions[1]?.version }}</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td>版本状态</td>
                      <td>{{ getStatusText(compareVersions[0]?.status) }}</td>
                      <td>{{ getStatusText(compareVersions[1]?.status) }}</td>
                    </tr>
                    <tr>
                      <td>创建人</td>
                      <td>{{ compareVersions[0]?.creator }}</td>
                      <td>{{ compareVersions[1]?.creator }}</td>
                    </tr>
                    <tr>
                      <td>执行次数</td>
                      <td>{{ compareVersions[0]?.executionCount }} 次</td>
                      <td>{{ compareVersions[1]?.executionCount }} 次</td>
                    </tr>
                    <tr>
                      <td>版本说明</td>
                      <td>{{ compareVersions[0]?.description || '暂无说明' }}</td>
                      <td>{{ compareVersions[1]?.description || '暂无说明' }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="触发条件" name="triggers">
              <div class="compare-section">
                <p>触发条件对比功能开发中...</p>
              </div>
            </el-tab-pane>
            <el-tab-pane label="执行步骤" name="steps">
              <div class="compare-section">
                <p>执行步骤对比功能开发中...</p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="compareVisible = false">关闭</el-button>
          <el-button type="info" @click="exportComparison">
            <el-icon>
              <Download />
            </el-icon>
            导出对比报告
          </el-button>
        </div>
      </template>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  View,
  Download,
  Search,
  Refresh
} from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  planData: any
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'version-changed', version: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  planData: () => ({})
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 当前版本信息
const currentVersion = ref({
  id: 1,
  planName: '防洪应急预案',
  version: 'v1.2',
  status: 'active',
  creator: '张三',
  createTime: '2024-01-15 10:30:00',
  effectiveTime: '2024-01-15 12:00:00',
  executionCount: 5,
  description: '修复了执行步骤中的问题，优化了通知机制',
  isCurrent: true
})

// 版本历史数据
const versionHistory = ref([
  {
    id: 1,
    version: 'v1.2',
    status: 'active',
    creator: '张三',
    createTime: '2024-01-15 10:30:00',
    description: '修复了执行步骤中的问题，优化了通知机制',
    executionCount: 5,
    isCurrent: true
  },
  {
    id: 2,
    version: 'v1.1',
    status: 'obsolete',
    creator: '李四',
    createTime: '2024-01-10 14:20:00',
    description: '增加了新的触发条件，调整了执行流程',
    executionCount: 12,
    isCurrent: false
  },
  {
    id: 3,
    version: 'v1.0',
    status: 'obsolete',
    creator: '王五',
    createTime: '2024-01-05 09:15:00',
    description: '初始版本，包含基本的防洪预案功能',
    executionCount: 8,
    isCurrent: false
  }
])

// 搜索和分页
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selectedVersions = ref([])

// 创建版本相关
const createVersionVisible = ref(false)
const createVersionLoading = ref(false)
const createVersionFormRef = ref()
const createVersionForm = ref({
  version: '',
  baseVersion: '',
  type: '',
  description: '',
  activate: false
})

const createVersionRules = {
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  baseVersion: [
    { required: true, message: '请选择基于版本', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择版本类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入版本说明', trigger: 'blur' }
  ]
}

// 版本对比相关
const compareVisible = ref(false)
const compareTab = ref('basic')
const compareVersions = ref([])

// 计算属性
const filteredVersions = computed(() => {
  let filtered = versionHistory.value
  
  if (searchKeyword.value) {
    filtered = filtered.filter(version =>
      version.version.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      version.creator.includes(searchKeyword.value) ||
      version.description.includes(searchKeyword.value)
    )
  }
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

const totalVersions = computed(() => {
  let filtered = versionHistory.value
  
  if (searchKeyword.value) {
    filtered = filtered.filter(version =>
      version.version.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      version.creator.includes(searchKeyword.value) ||
      version.description.includes(searchKeyword.value)
    )
  }
  
  return filtered.length
})

const versionOptions = computed(() => {
  return versionHistory.value.map(version => ({
    id: version.id,
    version: version.version
  }))
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap = {
    'draft': 'info',
    'reviewing': 'warning',
    'active': 'success',
    'obsolete': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    'draft': '草稿',
    'reviewing': '审核中',
    'active': '生效',
    'obsolete': '已废止'
  }
  return textMap[status] || status
}

// 获取版本标签类型
const getVersionTagType = (version: any) => {
  if (version.isCurrent) return 'success'
  if (version.status === 'active') return 'primary'
  if (version.status === 'obsolete') return 'info'
  return 'warning'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedVersions.value = selection
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 刷新版本列表
const refreshVersions = () => {
  ElMessage.success('版本列表已刷新')
}

// 查看版本
const viewVersion = (version: any) => {
  ElMessage.info(`查看版本 ${version.version} 功能开发中...`)
}

// 激活版本
const activateVersion = async (version: any) => {
  try {
    await ElMessageBox.confirm(`确认激活版本 ${version.version}？`, '确认激活', {
      type: 'warning'
    })
    
    // 更新版本状态
    versionHistory.value.forEach(v => {
      v.isCurrent = v.id === version.id
      if (v.id === version.id) {
        v.status = 'active'
      }
    })
    
    currentVersion.value = { ...version, isCurrent: true }
    
    ElMessage.success(`版本 ${version.version} 已激活`)
    emit('version-changed', version)
    
  } catch {
    // 用户取消
  }
}

// 回滚版本
const rollbackVersion = async (version: any) => {
  try {
    await ElMessageBox.confirm(`确认回滚到版本 ${version.version}？`, '确认回滚', {
      type: 'warning'
    })
    
    ElMessage.success(`已回滚到版本 ${version.version}`)
    
  } catch {
    // 用户取消
  }
}

// 删除版本
const deleteVersion = async (version: any) => {
  try {
    await ElMessageBox.confirm(`确认删除版本 ${version.version}？`, '确认删除', {
      type: 'warning'
    })
    
    const index = versionHistory.value.findIndex(v => v.id === version.id)
    if (index > -1) {
      versionHistory.value.splice(index, 1)
    }
    
    ElMessage.success(`版本 ${version.version} 已删除`)
    
  } catch {
    // 用户取消
  }
}

// 显示创建版本对话框
const showCreateVersionDialog = () => {
  createVersionForm.value = {
    version: '',
    baseVersion: currentVersion.value.id,
    type: '',
    description: '',
    activate: false
  }
  createVersionVisible.value = true
}

// 创建新版本
const handleCreateVersion = async () => {
  try {
    await createVersionFormRef.value.validate()
    
    createVersionLoading.value = true
    
    // 模拟创建版本API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const newVersion = {
      id: Date.now(),
      version: createVersionForm.value.version,
      status: createVersionForm.value.activate ? 'active' : 'draft',
      creator: '当前用户',
      createTime: new Date().toISOString(),
      description: createVersionForm.value.description,
      executionCount: 0,
      isCurrent: createVersionForm.value.activate
    }
    
    // 如果激活新版本，更新其他版本状态
    if (createVersionForm.value.activate) {
      versionHistory.value.forEach(v => {
        v.isCurrent = false
      })
      currentVersion.value = { ...newVersion, isCurrent: true }
    }
    
    versionHistory.value.unshift(newVersion)
    
    ElMessage.success('新版本创建成功')
    createVersionVisible.value = false
    
  } catch (error) {
    ElMessage.error('表单验证失败')
  } finally {
    createVersionLoading.value = false
  }
}

// 显示版本对比对话框
const showCompareDialog = () => {
  if (selectedVersions.value.length !== 2) {
    ElMessage.warning('请选择两个版本进行对比')
    return
  }
  
  compareVersions.value = [...selectedVersions.value]
  compareVisible.value = true
}

// 显示版本合并对话框
const showMergeDialog = () => {
  ElMessage.info('版本合并功能开发中...')
}

// 导出版本历史
const exportVersionHistory = () => {
  ElMessage.success('版本历史导出功能开发中...')
}

// 导出对比报告
const exportComparison = () => {
  ElMessage.success('对比报告导出功能开发中...')
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 组件挂载时初始化
onMounted(() => {
  if (props.planData) {
    currentVersion.value = {
      ...currentVersion.value,
      planName: props.planData.planName || currentVersion.value.planName
    }
  }
})
</script>

<style scoped>
.version-manage {
  max-height: 70vh;
  overflow-y: auto;
}

.current-version-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.info-item label {
  font-weight: bold;
  color: #666;
  min-width: 100px;
  margin-right: 10px;
}

.info-item span {
  color: #333;
}

.description {
  margin: 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  color: #333;
  line-height: 1.6;
}

.action-buttons {
  margin: 20px 0;
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.history-card {
  margin-bottom: 20px;
}

.version-cell {
  display: flex;
  align-items: center;
}

.description-text {
  color: #666;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.version-compare {
  padding: 20px 0;
}

.compare-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.version-info {
  text-align: center;
  flex: 1;
}

.version-info h4 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 18px;
}

.version-info span {
  color: #666;
  font-size: 14px;
}

.compare-divider {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin: 0 30px;
}

.compare-content {
  margin-top: 20px;
}

.compare-table {
  width: 100%;
}

.comparison-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.comparison-table th,
.comparison-table td {
  border: 1px solid #dcdfe6;
  padding: 12px;
  text-align: left;
}

.comparison-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #333;
}

.comparison-table td {
  color: #666;
}

.compare-section {
  padding: 40px;
  text-align: center;
  color: #999;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-tabs--border-card) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.el-tab-pane) {
  padding: 20px;
}
</style>